<!-- 采购合同编辑 -->
<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field required :rules="[{ required: true }]" v-model="formData.billNumber" name="采购编号" label="采购编号" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.brandName" readonly name="品牌" label="品牌" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('brandId', 'brandName')" />
        <van-field required :rules="[{ required: true }]" v-model="formData.showOrgName" readonly name="归属展厅" label="归属展厅" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('showOrgId', 'showOrgName')" />
        <van-field required :rules="[{ required: true }]" v-model="formData.signCompany" name="签约公司" label="签约公司" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('signCompanyId', 'signCompany')" readonly />
        <van-field required :rules="[{ required: true }]" v-model="formData.signHall" name="签约展厅" label="签约展厅" input-align="right" placeholder="请选择" readonly />
        <!-- @click="handleSelect('signHallId', 'signHall')" -->

        <van-field v-model="formData.description" name="备注" label="备注" type="textarea" input-align="left" placeholder />
        <van-field required :rules="[{ required: true }]" v-model="formData.purReason" name="采购原因" label="采购原因" type="textarea" input-align="left" placeholder />
        <van-field required :rules="[{ required: true }]" v-model="formData.customerName" name="客户名称" label="客户名称" input-align="right" placeholder="请输入" />
        <van-field required clickable :rules="[{ required: true }]" v-model="formData.identity" name="身份证" label="身份证" input-align="right" placeholder="请输入" />

        <van-field required :rules="[{ required: true }]" v-model="formData.phoneNum" name="联系电话" label="联系电话" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.amount" name="采购金额" label="采购金额" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.shLimitPrice" name="销售限价" label="销售限价" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.salesTypeName" name="销售类型" label="销售类型" input-align="right" placeholder="请选择" readonly right-icon="arrow" @click="handleSelect('salesType', 'salesTypeName')" />
        <van-field required :rules="[{ required: true }]" v-model="formData.vinCode" name="车架号" label="车架号" input-align="right" placeholder="请输入" />
        <van-field v-model="formData.style" name="款式（年款）" label="款式（年款）" input-align="right" placeholder="请输入" />
        <van-field v-model="formData.entryNote" name="车辆备注" label="车辆备注" input-align="right" placeholder="请输入" />

        <van-field required :rules="[{ required: true }]" v-model="formData.shBrand" name="二手车品牌" label="二手车品牌" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.shInsideColor" name="内饰颜色" label="内饰颜色" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.shOutsideColor" name="外饰颜色" label="外饰颜色" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.shDisplacement" name="排量" label="排量" input-align="right" placeholder="请输入" />
        <van-field required :rules="[{ required: true }]" v-model="formData.shYCValidity" name="年检到期日" label="年检到期日" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelectTime('shYCValidity')" readonly />
        <van-field required :rules="[{ required: true }]" v-model="formData.shInsExpiryDate" name="保险到期日" label="保险到期日" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelectTime('shInsExpiryDate')" readonly />

        <van-field required :rules="[{ required: true }]" name="radio" label="是否客户寄售二手车" input-align="right" label-width="170px">
          <template #input>
            <van-radio-group v-model="formData.CSUsedCars" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field required :rules="[{ required: true }]" name="radio" label="是否新能源" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.isNewEnergy" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field required :rules="[{ required: true }]" name="radio" label="是否外拓资源" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.outsourceResources" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field required :rules="[{ required: true }]" name="radio" label="是否事故" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.shAccident" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in isflagList1" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field required :rules="[{ required: true }]" v-if="formData.shAccident == 0" v-model="formData.shAccidentNote" name="事故说明" label="事故说明" type="textarea" input-align="left" placeholder />

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field name="模糊查询" v-if="likeWhoField == 'signCompanyId'" input-align="left" v-model="likeWho" label="模糊查询" placeholder="请输入模糊查询关键词" />
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>

        <!-- 时间选择弹窗 -->
        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @confirm="onTimeConfirm($event)" @cancel="showTimerPicker = false" :formatter="formatter" />
        </van-popup>
        <div class="footerBtn">
          <div class="saveBtn" @click="formOnSubmit(1)">保存</div>
          <div class="submitBtn" @click="formOnSubmit(2)">提交</div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Tab,
  Tabs,
  Notify,
  Dialog
} from "vant";
import { getCookies } from "@/utils/util.js";
import sellManageApi from "@/api/sellManageApi";
import commonApi from "@/api/commonApi";
export default {
  name: "buyContractEdit",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    Tab,
    Tabs,
    Notify,
    Dialog
  },
  data() {
    return {
      showTimerPicker: false,
      formData: {
        billId: "", //单据ID
        billNumber: "", //单据编号
        billStatus: "", //单据状态
        entryId: "", //分录ID
        carNo: "", //车牌号
        videCode: "", //车架号
        carModel: "", //二手车型
        firstRegDate: "", //初等日期
        insExpiryDate: "", //保险到期日
        yCValidityDate: "", //年检到期日
        salesType: "", //销售类型
        shOutsideColor: "", //外饰颜色
        shInsideColor: "", //外饰颜色
        isNewEnergy: 0, //是否新能源
        isCSUsedCars: "", //是否客户寄售
        amount: "", //采购金额
        isPay: "", //是否付款
        payDate: "", //付款日期
        isCommit: "", //是否开票
        invoiceDate: "", //开票日期
        stockStatus: "", //入库状态
        stockDate: "", //入库日期
        brandName: "", //所属品牌
        brandId: "", //所属品牌
        showOrgName: "", //所属展厅
        showOrgId: "", //所属展厅
        signCompany: "", //签约公司
        signCompanyId: "", //签约公司
        bizDate: "", //签约日期
        followPerson: "", //采购人员
        customerName: "", //客户名称
        identity: "", //身份证
        phoneNum: "", //联系电话
        realPayAmt: "", //应付金额
        amountPaid: "", //已付金额
        remainingInvoiceAmount: "", //未开票金额
        carSuggess: "", //车辆推荐人
        leadsPurId: "", //采购线索id
        leadsShowOrgName: "", //推荐人展厅
        leadsFixcenterName: "", //推荐人维修中心
        vinCode: "",
        signCompany: "", //签约公司
        signCompanyId: "", //签约公司
        signHall: "", //签约展厅
        signHallId: "", //签约展厅
        identity: "", //身份证
        shLimitPrice: "", //销售限价,
        salesTypeValue: "", //销售类型值
        shDisplacement: "", //排量
        shYCValidity: "", //年检到期日
        shInsExpiryDate: "", //保险到期日
        shAccidentNote: "", //事故说明
        CSUsedCars: 0
      },

      columns: [],
      showSelectPicker: false,
      detailId: "",
      userId: getCookies("userId"), //用户ID，必填，String
      isflagList: [
        { name: "是", value: 1 },
        { name: "否", value: 0 }
      ],
      isflagList1: [
        { name: "是", value: 0 },
        { name: "否", value: 1 }
      ],
      currentDate: new Date(),
      showOrgList: [],
      companyOrgUnitList: [],
      brandList: [],
      likeWhoField: "",
      likeWho: ""
    };
  },

  watch: {
    "formData.shAccident": {
      handler: function(val, oldVal) {
        if (!val) {
          this.formData.shAccidentNote = "";
        }
      },
      deep: true,
      immediate: false
    },
    likeWho: function(nval, oval) {
      if (nval) {
        let newArr = this.companyOrgUnitList.filter(item => {
          return item.name.indexOf(nval) > -1;
        });
        console.log(newArr);
        this.columns = newArr;
      } else {
        this.columns = this.companyOrgUnitList;
      }
    }
  },

  mounted() {
    this.getSaleContractSaleType();
    this.getShowOrgByUser();
    this.getCompanyOrgUnit();
    this.getBrandList();
    if (this.$route.query) {
      this.detailId = this.$route.query.billId;
      this.getDetail(this.detailId);
    }
  },
  methods: {
    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          billId,
          method: "getPurchaseContractById"
        })
        .then(res => {
          if (res.code == 1) {
            for (const key in res.data) {
              if (res.data[key] == null || res.data[key] == undefined) {
                res.data[key] = "";
              }
            }
            res.data.salesTypeName = res.data.salesType;
            res.data.salesType = res.data.salesTypeValue;
            res.data.CSUsedCars = res.data.CSUsedCars ? 1 : 0;

            //  res.data.isNewEnergy =  res.data.isNewEnergy ? 1 : 0;
            res.data.isNewEnergy = Number(res.data.isNewENergy.value);
            res.data.shAccident = Number(res.data.shAccident.value);
            res.data.outsourceResources = res.data.outsourceResources ? 1 : 0;
            this.formData = res.data;

            console.log(this.formData);
          }
        });
    },
    // 获取销售类型
    getSaleContractSaleType() {
      commonApi
        .getEnums({
          key: "salesType",
          userId: this.userId
        })
        .then(res => {
          if (res.data) {
            this.saleContractSaleTypeList = res.data;
          }
        });
    },
    // 获取签约公司
    getCompanyOrgUnit() {
      sellManageApi
        .secondHandCarFacade({
          method: "getComponyOrgUnit"
        })
        .then(res => {
          if (res.code == 1) {
            console.log(res.data);
            this.companyOrgUnitList = res.data;
          }
        });
    },

    // 获取展厅
    getShowOrgByUser(billId) {
      sellManageApi
        .secondHandCarFacade({
          method: "getShowOrgByUser",
          orgKey: "showOrg"
        })
        .then(res => {
          if (res.code == 0) {
            this.showOrgList = res.data;
            // this.showOrgList.forEach((item) => {
            //   if (localStorage.getItem("orgId") == item.billId) {
            //     this.formData.showOrgId = item.billId;
            //     this.formData.showOrgName = item.name;
            //   }
            // });
          }
        });
    },
    // 获取品牌
    getBrandList(billId) {
      sellManageApi
        .secondHandCarFacade({
          method: "getShowOrgByUser",
          orgKey: "brandAll"
        })
        .then(res => {
          if (res.code == 0) {
            this.brandList = res.data;
          }
        });
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "salesType") {
        this.columns = this.saleContractSaleTypeList;
      } else if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "signHallId") {
        this.columns = this.showOrgList;
      } else if (field == "signCompanyId") {
        this.columns = this.companyOrgUnitList;
      } else if (field == "brandId") {
        this.columns = this.brandList;
      }

      this.field = field;
      this.likeWhoField = field;
      this.fieldName = fieldName;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      if (this.field == "showOrgId") {
        this.formData[this.field] = value.billId;
        this.formData[this.fieldName] = value.name;
      } else {
        this.formData[this.field] = value.value;
        this.formData[this.fieldName] = value.name;
      }

      if (this.field == "signCompanyId") {
        this.formData[this.field] = value.billId;
        this.formData[this.fieldName] = value.name;
        this.formData.signHall = value.signHallName;
        this.formData.signHallId = value.signHallId;
      }

      this.showSelectPicker = false;
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[field] = `${year}-${month}-${day}`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    // 时间选择
    handleSelectTime(field) {
      this.timeField = field;
      this.showTimerPicker = true;
    },
    onTimeConfirm(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[this.timeField] = `${year}-${month}-${day} `;
      this.showTimerPicker = false;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    formOnSubmit(type) {
      this.$refs.form
        .validate()
        .then(() => {
          if (this.formData.vinCode && this.formData.vinCode.length != 17) {
            Notify({ type: "danger", message: "车架号长度必须17位" });
            return;
          }
          if (
            this.formData.shLimitPrice <
            (this.formData.amount * 1.05) / 100
          ) {
            Notify({
              type: "danger",
              message: "销售限价必须大于等于采购金额*1.05%"
            });
            return;
          }
          if (
            type == 2 &&
            this.formData.shLimitPrice < this.formData.amount * 1.05
          ) {
            Dialog.confirm({
              title: "提示",
              message: "二手车采购合同限价低于折后金额上浮5%，是否继续提交”"
            })
              .then(() => {
                sellManageApi
                  .secondHandCarFacade({
                    ...this.formData,
                    method: "updatePurchaseContract",
                    saveOrSubmit: type == 1 ? "save" : "submit"
                  })
                  .then(res => {
                    console.log(res);
                    if (res.code == 1) {
                      if (type == 1) {
                        Notify({ type: "success", message: "保存成功" });
                        // this.formData.billId = res.billId;
                      } else {
                        Notify({ type: "success", message: "提交成功" });
                        this.$router.go(-1);
                      }
                    }
                  });
              })
              .catch(() => {
                console.log("取消");
                // on cancel
              });
          } else {
            sellManageApi
              .secondHandCarFacade({
                ...this.formData,
                method: "updatePurchaseContract",
                saveOrSubmit: type == 1 ? "save" : "submit"
              })
              .then(res => {
                console.log(res);
                if (res.code == 1) {
                  if (type == 1) {
                    Notify({ type: "success", message: "保存成功" });
                    // this.formData.billId = res.billId;
                  } else {
                    Notify({ type: "success", message: "提交成功" });
                    this.$router.go(-1);
                  }
                }
              });
          }

          this.loading = true;
        })
        .catch(res => {
          console.log(res);
          this.loading = false;
          // let msg = "请完善信息," + res.map((res) => res.name);
          let msg = "请完善信息";
          this.$toast.fail(msg);
          // this.$toast.fail("请完善信息");
        });
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 10px 10px;
    border-radius: 5px;
    background: #fff;
    padding: 15px;
    .detail_header_lt {
      .carNo {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
        .carStatus {
          border: 1px solid #35bc04;
          color: #35bc04;
          border-radius: 5px;
          padding: 5px 5px;
          font-size: 12px;
          text-align: center;
          margin-left: 5px;
        }
      }
      .hank {
        font-size: 14px;
        color: #666;
        .name {
          border-right: 2px solid #ccc;
          padding-right: 5px;
          margin-right: 5px;
        }
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 14px;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 16px;
        padding: 5px;
        border-radius: 50%;
        margin-right: 5px;
      }
    }
  }
  .formData {
    background: #fff;
    overflow: hidden;
  }
}

.footerBtn {
  display: flex;
  justify-content: space-between;
  width: 80%;
  margin: auto;
  padding-bottom: 5px;
  background: #fff;
  margin-top: 25px;
  .saveBtn {
    background: #ccc;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
    margin-right: 10px;
  }
  .submitBtn {
    background: #409eff;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
  }
}
</style>
